<?php
/* ******************************
 *	Overhead Out aJax actions
 * ******************************
 */

include('../../../includes/classes/core.php');
 
$action 	= $_REQUEST['act'];
$error		= '';
$data		= '';
$user_id	= $_SESSION['USERID'];

switch ($action) {
    case 'get_add_page':
		$page	= GetPage();
		$data	= array('page'	=> $page);
		
        break;
    case 'get_edit_page':
	    $goods_id	= $_REQUEST['id'];
	    $o_type		= $_REQUEST['ot'];
	    
	    if(empty($o_type)){
			$page = GetPage(GetGoods($goods_id));
	    }else{	    
			$page = GetSubPage(GetGoods($goods_id), $o_type);        
	    }
        $data = array('page'	=> $page);
        
        break;
    case 'get_list':
	    $count		= $_REQUEST['count'];
	    $hidden		= $_REQUEST['hidden'];
	    $local_id	= $_REQUEST['local_id'];
	    
	    mysql_query("SET @i = 0;");    	    
	    $rResult = mysql_query("SELECT  `OD`.`id` AS `id`,
							  			@i := @i + 1 AS `iterator`,
							  			`OD`.`bar_code`,
										`OD`.`name` AS `goods_name`,
										`UN`.`name` AS `unit`,
										`OD`.`quantity`,
										`OD`.`price`,
										`OD`.`amount`
								FROM `overhead_detail` AS `OD` LEFT JOIN `production_unit` AS `UN`
									ON `OD`.`unit_id` = `UN`.`id`
								WHERE `overhead_id` = $local_id");
		
		$data = array(
			"aaData"	=> array()
		);
		
		if(!$rResult){
		    $error = 'Invalid query: ' . mysql_error();
		    
		}else{
			while ( $aRow = mysql_fetch_array( $rResult ) )
			{
				$row = array();
				for ( $i = 0 ; $i < $count ; $i++ )
				{
					/* General output */
					$row[] = $aRow[$i];
					if($i == ($count - 1)){
						$row[] = '<input type="checkbox" name="check_' . $aRow[$hidden] . '" class="check" value="' . $aRow[$hidden] . '" />';
					}
				}
				$data['aaData'][] = $row;
			}
		}

        break;
    case 'get_sub_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];
	    $par_id = $_REQUEST['local_id'];
	    
	    mysql_query("SET @i = 0;");    	    
	    $rResult = mysql_query("SELECT  `OD`.`id` AS `id`,
							  			@i := @i + 1 AS `iterator`,
							  			`OD`.`bar_code`,
										`OD`.`name` AS `goods_name`,
										`UN`.`name` AS `unit`,
										`OD`.`quantity`,
										`OD`.`price`,
										`OD`.`amount`,
										`OD`.`quantity_f`
								FROM `overhead_detail` AS `OD` LEFT JOIN `production_unit` AS `UN`
									ON `OD`.`unit_id` = `UN`.`id`
								WHERE `overhead_id` = $par_id");
		
		$data = array(
			"aaData"	=> array()
		);
		
		if (!$rResult) {
		    $error = 'Invalid query: ' . mysql_error();
		    
		} else {
			while ( $aRow = mysql_fetch_array( $rResult ) )
			{
				$row = array();
				for ( $i = 0 ; $i < $count ; $i++ )
				{
					/* General output */
					$row[] = $aRow[$i];
				}
				$data['aaData'][] = $row;
			}
		}

        break;
    case 'save_prod':
		$goods_id 		= $_REQUEST['id'];
		$local_id 		= $_REQUEST['li'];
		
		$obj_id 		= $_REQUEST['obj'];
		
		$code	 		= $_REQUEST['gc'];
		$name 			= htmlspecialchars($_REQUEST['gn'], ENT_QUOTES);
		$measure	 	= $_REQUEST['gm'];
		$quantity	 	= $_REQUEST['gq'];
		$unit_price	 	= $_REQUEST['gu'];
		$price	 		= $_REQUEST['gp'];
		$vat	 		= $_REQUEST['gv'];
		$quantity_f		= $_REQUEST['qf'];
		
		$prod_id		= GetGoodsDetails($code, $name);
		
		$exist_c		= CheckGoodsExist($code, '', $local_id);
		$exist_n		= CheckGoodsExist('', $name, $local_id);
		
		$quantity_c		= CheckQuantity($prod_id['id'], $obj_id, $quantity);
		
		if($quantity_c){
			if(empty($goods_id)){		
				if($quantity_f == ''){
					$quantity_f = $quantity;
				}
				if($exist_c){
					if($exist_n){
						AddGoods($user_id, $local_id, $prod_id['id'], $code, $name, $measure, $quantity, $unit_price, $price, $vat, $quantity_f);					
					}else{
						$error = '"' . $name . '" უკვე შეტანილია!';
					}
				}else{
					$error = 'საქონელი ასეთი კოდით უკვე შეტანილია!';
				}
			}else{					
				$goods = GetGoods($goods_id);
				
				if($quantity_f == ''){
					$quantity_f = $quantity;
				}else{
					$quantity_f = $quantity_f + $goods['quantity'];
					$quantity_f = $quantity_f - $quantity;
				}
			
				if($quantity_f >= 0){
					SaveGoods($user_id, $goods_id, $quantity, $price, $unit_price, $vat, $quantity_f);
				}else{
					$error = 'რაოდენობა აღემატება ნაშთს!';
				}
			}
		}else{
			$error = 'არასაკმარისი პროდუქტი მარაგში!';
		}
		
        break;
    case 'add_sub_goods':
    	$overhead_id	= $_REQUEST['o_id'];
    	$parent_id		= $_REQUEST['parent_id'];
		$goods			= GetGoodsList($parent_id);
		
	    while( $res = mysql_fetch_assoc($goods)){
			AddGoods($user_id, $overhead_id, $res['goods_id'], $res['bar_code'], $res['name'], $res['unit_id'], 0, $res['price'], 0, $res['vat_type'], $res['quantity']);
		}
				
        break;
    case 'disable':
		$goods_id 		= $_REQUEST['id'];
		DeleteGoods($goods_id);
		
        break;
    case 'get_goods':
		$barcode 		= $_REQUEST['bc'];
		$name 			= $_REQUEST['nm'];	
		$res 			= GetGoodsDetails($barcode, $name);			
		if(!$res){
			$error = 'საქონელი ვერ მოიძებნა!';
		}else{	
			$data = array('code' => $res['code'],
						  'name' => $res['name'],
						  'measure' => $res['unit'],
						  'price' => $res['price']);
		}
		
        break;
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Overhead Out Functions
 * ******************************
 */

function AddGoods($user_id, $local_id, $prod_id, $code, $name, $measure, $quantity, $unit_price, $price, $vat, $quantity_f)
{
	mysql_query("INSERT INTO `overhead_detail`
					(`user_id`, `overhead_id`, `goods_id`, `name`, `unit_id`, `quantity`, `price`, `amount`, `bar_code`, `vat_type`, `quantity_f`) 
				 VALUES
					($user_id, '$local_id', $prod_id, '$name', $measure, $quantity, $unit_price, $price, '$code', $vat, $quantity_f)");
}

function SaveGoods($user_id, $goods_id, $quantity, $unit_price, $price, $vat, $quantity_f)
{
	mysql_query("UPDATE
	    			`overhead_detail`
				 SET
				 	`user_id`	= $user_id,
				    `quantity`	= $quantity,
				    `price`		= $price,
				    `amount`	= $unit_price,
				    `quantity_f`= $quantity_f
				 WHERE
					`id`		= $goods_id");
}
	
function CheckGoodsExist($code, $name, $local_id) 
{
	if($code != ''){
	    $res = mysql_query("SELECT	`id`
						    FROM	`overhead_detail`
						    WHERE	`bar_code` = '$code' && `overhead_id` = $local_id");
	}else{
	    $res = mysql_query("SELECT	`id`
						    FROM	`overhead_detail`
						    WHERE	`name` = '$name' && `overhead_id` = $local_id");
	}
	
	if (mysql_num_rows($res) == 0){
		return true;
	}
	return false;
}


function CheckQuantity($prod_id, $obj_id, $req_quantity)
{
	$res = mysql_query("SELECT	SUM(`quantity` - `sold`) AS `quantity`
						FROM	`reserve`
						WHERE	`production_id` = $prod_id && `object_id` = $obj_id");
	$row = mysql_fetch_assoc($res);
	if($row['quantity'] >= $req_quantity){
		return true;
	}
	return false;
}

function DeleteGoods($goods_id)
{
    mysql_query("DELETE 
				 FROM
	    			`overhead_detail`
				 WHERE
					`id` = $goods_id");
}

function GetUnit($point)
{
	$data = '';
    $req = mysql_query("SELECT	`id`,
    							`name`
						FROM	`production_unit`");
	
	if($point == ''){
		$data = '<option value="0" selected="selected"></option>';
	}
	
	while( $res = mysql_fetch_assoc($req)){			
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}				
	}
	
	return $data;
}
	
function GetVat($point)
{
	$data = '';
    $req = mysql_query("SELECT	`id`,
    							`name`
						FROM `overhead_vat`");
		
	while( $res = mysql_fetch_assoc($req)){			
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}				
	}
		
	return $data;
}
		
function GetGoodsDetails($code, $name) 
{
	if($code != '' && $name != ''){
		$res = mysql_query("	SELECT	`PROD`.`id`,
										`PROD`.`code`,
										`PROD`.`name`,
										`PROD`.`unit`,
										`PCL`.`price`
								FROM `production` AS `PROD` INNER JOIN `pricelist` AS `PCL`
									ON `PROD`.`id` = `PCL`.`production_id`
								WHERE `PROD`.`code` = '$code' && `PROD`.`name` = '$name'");
	}else if($code != ''){
		$res = mysql_query("	SELECT	`PROD`.`code`,
										`PROD`.`name`,
										`PROD`.`unit`,
										`PCL`.`price`
								FROM `production` AS `PROD` INNER JOIN `pricelist` AS `PCL`
									ON `PROD`.`id` = `PCL`.`production_id`
								WHERE `PROD`.`code` = '$code'");
	}else if($name != ''){
		$res = mysql_query("	SELECT	`PROD`.`code`,
										`PROD`.`name`,
										`PROD`.`unit`,
										`PCL`.`price`
								FROM `production` AS `PROD` INNER JOIN `pricelist` AS `PCL`
									ON `PROD`.`id` = `PCL`.`production_id`
								WHERE `PROD`.`name` = '$name'");
	}
	
	if (mysql_num_rows($res) == 0){
		return false;
	}
	$row = mysql_fetch_assoc($res);
	return $row;
}

function GetGoodsList($overhead_id) 
{
    $res = mysql_query("SELECT 	`id`,
    						  	`goods_id`,
						       	`name`,
						      	`unit_id`,
						   	  	`quantity`,
						   	   	`price`,
						   	  	`amount`,
							   	`bar_code`,
						   	   	`vat_type`
				      	FROM	`overhead_detail`
				      	WHERE	`overhead_id` = $overhead_id");
	return $res;
}

function GetGoods($goods_id) 
{
    $res = mysql_fetch_assoc(mysql_query("SELECT `id`,
    											 `bar_code`,
											     `name`,
											     `unit_id`,
											   	 `quantity`,
											   	 `price`,
											   	 `amount`,
											   	 `vat_type`,
											   	 `quantity_f`
									      FROM `overhead_detail`
									      WHERE `id` = $goods_id"));
	return $res;
}

function GetPage($res = '')
{
	$data = '		
	<div id="dialog-form">
	    <fieldset>
	    	<legend>ძირითადი ინფორმაცია</legend>
	    	
	    	<table class="dialog-form-table">
				<tr>
					<td style="width: 170px;"><label for="goods_code">საქონლის კოდი</label></td>
					<td>
						<input type="text" id="goods_code" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['bar_code'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_name">საქონლის დასახელება</label></td>
					<td>
						<div class="seoy-row" id="goods_name_seoy">
							<input type="text" id="goods_name" class="idle seoy-address" onblur="this.className=\'idle seoy-address\'" onfocus="this.className=\'activeField seoy-address\'" value="' . $res['name'] . '" />
							<button id="goods_name_btn" class="combobox">goods_name</button>
						</div>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_measure">ზომის ერთეული</label></td>
					<td>
						<select id="goods_measure" class="idls num" disabled="disabled">' . GetUnit($res[unit_id]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_quantity">რაოდენობა</label></td>
					<td>
						<input type="text" id="goods_quantity" class="idle num" onblur="this.className=\'idle num\'" onfocus="this.className=\'activeField num\'" value="' . $res['quantity'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_unit_price">ერთეულის ფასი</label></td>
					<td>
						<input type="text" id="goods_unit_price" disabled="disabled" class="idle num" onblur="this.className=\'idle num\'" onfocus="this.className=\'activeField num\'" value="' . $res['price'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_price">საქონლის ფასი</label></td>
					<td>
						<input type="text" id="goods_price" disabled="disabled" class="idle num" onblur="this.className=\'idle num\'" onfocus="this.className=\'activeField num\'" value="' . $res['amount'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_vat">დაბეგვრა</label></td>
					<td>
						<select id="goods_vat" class="idls medium">' . GetVat($res[vat_type]) . '</select>
					</td>
				</tr>
			</table>
			<!-- ID -->
			<input type="hidden" id="goods_id" value="' . $res['id'] . '" />
        </fieldset>
    </div>
    
    ';
	return $data;
}

function GetSubPage($res = '')
{
	$data = '
	<div id="dialog-form">
	    <fieldset>
	    	<legend>ძირითადი ინფორმაცია</legend>
	    	
	    	<table class="dialog-form-table">
				<tr>
					<td style="width: 170px;"><label for="goods_code">საქონლის კოდი</label></td>
					<td>
						<input type="text" id="goods_code" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['bar_code'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_name">საქონლის დასახელება</label></td>
					<td>
						<div class="seoy-row" id="goods_name_seoy">
							<input type="text" id="goods_name" class="idle seoy-address" onblur="this.className=\'idle seoy-address\'" onfocus="this.className=\'activeField seoy-address\'" value="' . $res['name'] . '" />
							<button id="goods_name_btn" class="combobox">goods_name</button>
						</div>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_measure">ზომის ერთეული</label></td>
					<td>
						<select id="goods_measure" class="idls num" disabled="disabled">' . GetUnit($res[unit_id]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_quantity">რაოდენობა</label></td>
					<td>
						<input type="text" id="goods_quantity" class="idle num" onblur="this.className=\'idle num\'" onfocus="this.className=\'activeField num\'" value="' . $res['quantity'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_residual">ნაშთი რაოდენობ</label></td>
					<td>
						<input type="text" id="goods_residual" disabled="disabled" class="idle num" onblur="this.className=\'idle num\'" onfocus="this.className=\'activeField num\'" value="' . $res['quantity_f'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_unit_price">ერთეულის ფასი</label></td>
					<td>
						<input type="text" id="goods_unit_price" disabled="disabled" class="idle num" onblur="this.className=\'idle num\'" onfocus="this.className=\'activeField num\'" value="' . $res['price'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="goods_price">საქონლის ფასი</label></td>
					<td>
						<input type="text" id="goods_price" disabled="disabled" class="idle num" onblur="this.className=\'idle num\'" onfocus="this.className=\'activeField num\'"/>
					</td>
				</tr>
			</table>
			<!-- ID -->
			<input type="hidden" id="goods_id" value="' . $res['id'] . '" />
        </fieldset>
    </div>
    
    ';
	return $data;
}

?>